import api, { getResponseCount } from '@/store/api';
import i18n from '@/i18n';
const { t } = i18n.global as any;

type SessionSettingsForm = {
  SessionTimeout: number;
};

export const useSessionsStore = defineStore('sessions', () => {
  const allConnections = ref([] as any[]);
  const sessionTimeout = ref(0);

  const setAllConnections = (connections: any) =>
    (allConnections.value = connections);
  const setSessionTimeout = (timeout: number) =>
    (sessionTimeout.value = timeout);

  const getSessionsData = async () => {
    return await api
      .get('/redfish/v1/SessionService/Sessions')
      .then((response) =>
        response.data.Members.map(
          (sessionLogs: { [x: string]: any }) => sessionLogs['@odata.id'],
        ),
      )
      .then((sessionUris) =>
        api.all(sessionUris.map((sessionUri: string) => api.get(sessionUri))),
      )
      .then((sessionUris: { [index: string]: any }) => {
        const allConnectionsData = sessionUris.map(
          (sessionUri: { data?: any }) => {
            return {
              clientID: sessionUri.data?.Oem?.OpenBMC.ClientID,
              username: sessionUri.data?.UserName,
              ipAddress: sessionUri.data?.ClientOriginIPAddress,
              uri: sessionUri.data['@odata.id'],
            };
          },
        );
        setAllConnections(allConnectionsData);
      })
      .catch((error) => {
        console.log('Client Session Data:', error);
      });
  };
  const disconnectSessions = async (uris: string[] = []) => {
    const promises = uris.map((uri) =>
      api.delete(uri, undefined).catch((error) => {
        console.log(error);
        return error;
      }),
    );
    return await api
      .all(promises)
      .then((response) => {
        getSessionsData();
        return response;
      })
      .then(
        api.spread((...responses) => {
          const { successCount, errorCount } = getResponseCount(responses);
          const toastMessages = [];

          if (successCount) {
            const message = t('pageSessions.toast.successDelete', successCount);
            toastMessages.push({ type: 'success', message });
          }

          if (errorCount) {
            const message = t('pageSessions.toast.errorDelete', errorCount);
            toastMessages.push({ type: 'error', message });
          }
          return toastMessages;
        }),
      );
  };
  const getSessionTimeout = async () => {
    return api
      .get('/redfish/v1/SessionService/')
      .then(({ data: { SessionTimeout } }) => {
        setSessionTimeout(SessionTimeout);
      });
  };
  const patchSessionTimeout = async (payload: SessionSettingsForm) => {
    return api
      .patch('/redfish/v1/SessionService/', payload)
      .then(async () => {
        getSessionTimeout();
      })
      .catch((err) => {
        throw err;
      });
  };
  const commitSessionSettings = async (payload: SessionSettingsForm) => {
    const promises: Promise<any>[] = [];
    const p = patchSessionTimeout({
      SessionTimeout: payload.SessionTimeout,
    });
    promises.push(p);
    await Promise.all(promises).catch((err) => {
      throw err;
    });
  };

  return {
    allConnections,
    sessionTimeout,
    setAllConnections,
    setSessionTimeout,
    getSessionsData,
    disconnectSessions,
    getSessionTimeout,
    patchSessionTimeout,
    commitSessionSettings,
  };
});
